﻿namespace UsefulTools.ExtensionMethods
{
    using System;

    public static class Numbers
    {
        /// <summary>
        /// Returns the value incremented if the condition is true or the value unchanged otherwise.
        /// </summary>
        /// <param name="value"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public static int IncrementedIf(this int value, bool condition)
        {
            return condition ? value + 1 : value;
        }

        /// <summary>
        /// Returns the <paramref name="part"/> value as percent value of <paramref name="all"/> value. Returned number is from range [0, 100].
        /// </summary>
        /// <param name="part"></param>
        /// <param name="all"></param>
        /// <returns></returns>
        public static int AsPercentageOf(this int part, int all)
        {
            Throw.If(part < 0 || all <= 0 || part > all,
                "Value 'part' (current: "+part+") should be > 0 and <= 'all' and 'all' (current: "+all+") should be > 0.");
            return (int)Math.Floor(((double)part / all) * 100);
        }
        /// <summary>
        /// Returns the <paramref name="part"/> value as percent value of <paramref name="all"/> value. Returned number is from range [0, 100].
        /// </summary>
        /// <param name="part"></param>
        /// <param name="all"></param>
        /// <returns></returns>
        public static int AsPercentageOf(this double part, double all)
        {
            Throw.If(part < 0 || part > all || all < 0.000000001,
                "Value 'part' (current: "+part+") should be > 0 and <= 'all' and 'all' (current: "+all+") should be > 0.");
            return (int)Math.Floor((part / all) * 100d);
        }

        /// <summary>
        /// Rounds the value to a number of given count of significant digits.
        /// </summary>
        /// <param name="number"></param>
        /// <param name="digits">Count of significant digits</param>
        /// <returns></returns>
        public static double RoundToSignificantDigits(this double number, int digits)
        {
            double scale = Math.Pow(10, Math.Floor(Math.Log10(number)) + 1);
            return scale * Math.Round(number / scale, digits);
        }
 
    }
}